import akshare as ak
import logging
import pandas as pd
from typing import List, Dict
from core import BaseDataAdapter
from datetime import datetime

logger = logging.getLogger(__name__)

class AKShareETFAdapter(BaseDataAdapter):
    """ETF基金数据适配器"""
    
    def __init__(self, *args,) -> None:
        super(AKShareETFAdapter).__init__(*args)
    
    @staticmethod
    def format_symbol(symbol: str) -> str:
        return symbol.replace('.SH', '').replace('.SZ', '').replace('.sh', '').replace('.sz', '')

    @classmethod
    async def get_historical_data(cls, symbol: str, start: datetime, end: datetime) -> List[Dict]:
        formatted_symbol = cls.format_symbol(symbol)
        try:
            df = ak.fund_etf_hist_sina(symbol=f"sh_{formatted_symbol}")
            return cls.validate_data(df)
        except Exception as e:
            logger.error(f"ETF数据获取失败: {str(e)}")
            return []

    @classmethod
    def validate_data(cls, df: pd.DataFrame) -> List[Dict]:
        return [{
            'date': row['date'].strftime("%Y-%m-%d"),
            'nav': round(row['unit_nav'], 4),
            'accum_nav': round(row['accumulated_nav'], 4),
            'premium_rate': round(row['premium_rate'], 2),
            'volume': int(row['volume'])
        } for _, row in df.iterrows()]